package com.hsgene.common.util.qiniu;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.hsgene.common.util.bean.SpringApplicationContextUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 七牛资源加签Serializer
 *
 * @author wangbing
 * @version 1.0, 2018/12/17
 */
public class QiniuListResourcesSerializer extends JsonSerializer<List<String>> {

    private final static Logger LOGGER = LoggerFactory.getLogger(QiniuListResourcesSerializer.class);

    private RedisTemplate redisTemplate = (RedisTemplate) SpringApplicationContextUtil.getBean("redisTemplate");

    @Override
    public void serialize(List<String> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (CollectionUtils.isEmpty(value)) {
            return;
        }
        try {
            gen.writeStartArray();
            value.forEach(item -> {
                try {
                    if (redisTemplate != null) {
                        String url = item.split("\\?")[0];
                        String redisKey = QiniuResourceSerializer.IMAGE_REDIS_PREFIX + url.hashCode();
                        String token = (String) redisTemplate.opsForValue().get(redisKey);
                        if (StringUtils.isNotBlank(token)) {
                            gen.writeString(url + "?" + token);
                        } else {
                            String signUrl = QiniuCertificateUtil.getDownloadCertificateStr(url);
                            if (StringUtils.isNotBlank(signUrl)) {
                                String[] data = signUrl.split("\\?");
                                if (data.length == 2) {
                                    redisTemplate.opsForValue().set(redisKey, data[1], QiniuResourceSerializer.IMAGE_REDIS_EXPIRES, TimeUnit.SECONDS);
                                }
                            }
                            gen.writeString(signUrl);
                        }
                    } else {
                        gen.writeString(QiniuCertificateUtil.getDownloadCertificateStr(item));
                    }
                } catch (IOException e) {
                    LOGGER.error("七牛资源签名异常：{}", item);
                    LOGGER.error(e.getMessage(), e);
                }
            });
            gen.writeEndArray();
        } catch (Exception e) {
            LOGGER.error("七牛资源签名异常：{}", value);
            LOGGER.error(e.getMessage(), e);
        }
    }
}
